package com.etrans.web.gps.business.base.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.base.domain.PlatformVO;
import com.etrans.web.gps.business.base.service.PlatformService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.grid.FlexiGridUtil;


/**
 * 平台信息管理Controller
 * @author zhangw
 *
 */
@Controller
@RequestMapping(value="/base/platform/*")
public class PlatformController extends BaseController {
	
	private final static Logger logger = LoggerFactory.getLogger("PlatformController");
	
	@Autowired
	private PlatformService platformService;
	
	/**
	 *跳转平台信息管理
	 * @Description 页面跳转
	 */
	@RequestMapping("getPlatformManager.html")
	public String getLoginRecord(){
		return "views/business/base/platform/platformManager";
	}
	
	/**
	 * 分页查询平台信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loadPlatformList.html")
	public PageVo loadPlatformList(@RequestParam  String paramsGrid) {
		PageVo page = new PageVo();		
		Map<String, Object> paramMap =  FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		List<PlatformVO> platformList = platformService.queryPlatformList(paramMap);		
		page.setRows(platformList);
		page.setPage((int)paramMap.get("page"));
		page.setTotal(platformService.queryPlatformListCount(paramMap));
		return page;
	}
	
	/**
	 * 查询平台类型列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loadPlatformTypeList.html")
	public List<HashMap<String,Object>> loadPlatformTypeList(){
		List<HashMap<String,Object>> platformTypeList = platformService.queryPlatformTypeList();
		return platformTypeList;
	}

	/**
	 * 根据用户名查找平台数量
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryPlatformByName.html")
	public Map<String, Object> queryPlatformByName(String platformName) {
		Map<String, Object> result = new HashMap<>();
		Integer count = platformService.queryPlatformByName(platformName);
		result.put("count", count);
		return result;
	}
	
	/**
	 * 根据唯一编码查找平台数量
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryPlatformByUniCode.html")
	public Map<String, Object> queryPlatformByUniCode(String platformUniCode) {
		Map<String, Object> result = new HashMap<>();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("platformUniCode", platformUniCode);
		Integer count = platformService.queryCountByPlatformUniCode(paramMap);
		result.put("count", count);
		return result;
	}
	
	/**
	 * 跳转新增界面
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "initPlatformForm.html")
	public ModelAndView initPlatformForm() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("action", "insert");
		mav.addObject("platform", new PlatformVO());
		mav.setViewName("views/business/base/platform/addPlatformForm");
		return mav;
	}

	/**
	 * 新增和修改保存
	 * @return
	 */
	@RequestMapping(value = "savePlatformForm.html")
	@ResponseBody
	public Map<String, Object> savePlatformForm(String action, PlatformVO platform) {
		Map<String, Object> result = new HashMap<>();
		try {
			// 首先查看是否有重复的唯一编码
			HashMap<String, Object> paramMap = new HashMap<String, Object>();

			
			paramMap.put("platformUniCode", platform.getPlatformUniCode());
			if ("insert".equals(action)) {
				int Count = platformService.queryCountByPlatformUniCode(paramMap);
				if (Count == 0) {
					platformService.insertPlatform(platform);
					result.put("code", Constant.RETURN_OK_CODE);
					result.put("msg", "保存成功");
				} else {
					// 已经重复
					result.put("code", Constant.RETURN_Repent_CODE);
					result.put("msg", "唯一编码已被使用!");
				}
			}
			if ("update".equals(action)) {
				platformService.updatePlatform(platform);
				result.put("code", Constant.RETURN_OK_CODE);
				result.put("msg", "修改成功");
			}
		} catch (Exception e) {
			logger.error("", e);
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "保存失败!");
		}
		return result;
	}
	/**
	 * 回填修改信息
	 * @return
	 */
	@RequestMapping(value = "initUpdatePlatformForm.html")
	public String initUpdatePlatformForm(Model model,String platformId) {
		int id = Integer.parseInt(platformId);
		PlatformVO platform = platformService.queryPlatformById(id);
		model.addAttribute("platformId", platformId);
		model.addAttribute("action", "update");
		model.addAttribute("platform", platform);
		model.addAttribute("getM1", platform.getM1());
		return "views/business/base/platform/addPlatformForm";
	}
	
	/**
	 * 跳转详细页面
	 * @return
	 */
	@RequestMapping(value = "initDetailInfo.html")
	public String initDetailInfo(Model model,String platformId) {
		int id = Integer.parseInt(platformId);
		PlatformVO platform = platformService.queryPlatformById(id);
		model.addAttribute("platformId", platformId);
		model.addAttribute("action", "update");
		model.addAttribute("platform", platform);
		model.addAttribute("getM1", platform.getM1());
		return "views/business/base/platform/DetailInfo";
	}
	
	/**
	 * 批量删除平台信息
	 * @return
	 */
	@RequestMapping(value = "delPlatformList.html")
	@ResponseBody
	public Map<String, Object> delPlatformList(String platformIds) {
		Map<String, Object> result = new HashMap<>();
		try {
			if (platformIds != null && !"".equals(platformIds)) {
				String[] arrayplatformIds = platformIds.split(",");
				for (String perID : arrayplatformIds) {
					platformService.deletePlatformByID(Integer.parseInt(perID));
					result.put("code", Constant.RETURN_OK_CODE);
					result.put("msg", "修改成功!");
				}
			}
		} catch (Exception e) {
			logger.error("", e);
			e.printStackTrace();
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "删除失败!");
		}
		return result;
	}
	
	/**
	 * 导出报表
	 * @param response
	 * @param request
	 * @param paramsGrid 前端json格式的参数
	 * @param colModel 表头
	 * @param title 标题
	 * @param imgsrc 图片url,如果为null则不加载图片页
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="exportPlatforms.html")
	@ResponseBody
	public void exportPlatforms(HttpServletResponse response,HttpServletRequest request, String colModel,
			String title,String imgsrc){
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> paramMap=getReqParameters();
		String fromNumber = paramMap.get("fromNumber") == null ? "0" : String.valueOf(paramMap.get("fromNumber"));
		String pageSize = paramMap.get("pageSize") == null ? "0" : String.valueOf(paramMap.get("pageSize"));
		paramMap.replace("fromNumber", Integer.valueOf(fromNumber));
		paramMap.replace("pageSize", Integer.valueOf(pageSize));
		List<String> colModelList = JSON.parseObject(colModel, List.class);	
		List<PlatformVO> result =platformService.queryExportPlatforms(paramMap);	
		List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
		for(int i=0;i<result.size();i++){
			HashMap<String, Object> map = new HashMap<String, Object>();
			PlatformVO  obj=(PlatformVO)result.get(i);
			map.put("platformName",obj.getPlatformName() == null ? "" : obj.getPlatformName());
			map.put("pTypeName",obj.getpTypeName() == null ? "" : obj.getpTypeName());
			map.put("short_name",obj.getShort_name() == null ? "" : obj.getShort_name());
			map.put("platformUniCode",obj.getPlatformUniCode() == null ? "" : obj.getPlatformUniCode());
			map.put("accessCenterCode",obj.getAccessCenterCode() == null ? "" : obj.getAccessCenterCode());
/*			map.put("subIP",obj.getSubIP() == null ? "" : obj.getSubIP());
			map.put("subPort",obj.getSubPort() == null ? "" : obj.getSubPort());
			map.put("userId",obj.getUserId() == null ? "" : obj.getUserId());
			map.put("passWord",obj.getPassWord() == null ? "" : obj.getPassWord());*/
			map.put("owner_unit",obj.getOwner_unit() == null ? "" : obj.getOwner_unit());
			map.put("contact",obj.getContact() == null ? "" : obj.getContact());
			map.put("contactNumber",obj.getContactNumber() == null ? "" : obj.getContactNumber());
			map.put("email",obj.getEmail() == null ? "" : obj.getEmail());
			map.put("enableSms",obj.getEnable_sms() == null ? "" : ("1".equals(String.valueOf(obj.getEnable_sms()))? "启用":"停用"));
			map.put("enableEmail",obj.getEnable_email() == null ? "" : ("1".equals(String.valueOf(obj.getEnable_email()))? "启用":"停用"));
			map.put("softWareUnit",obj.getSoftWareUnit() == null ? "" : obj.getSoftWareUnit());
			map.put("techSupportUnit",obj.getTechSupportUnit() == null ? "" : obj.getTechSupportUnit());
			//map.put("rowver",String.valueOf(obj.getRowver()) == null ? "" : sdf.format(obj.getRowver()));
			map.put("memo",obj.getMemo() == null ? "" :obj.getMemo());
			rows.add(map);
		}
		
		int index=-1;
		List rowsList = new ArrayList<>();
		rowsList.add(rows);
		exportExl(request, response,title, removeHeadName(colModelList,index,-1),rowsList,null);
	}
}
